import request from '../request'
import Store from './index'
const _toString = Object.prototype.toString
class ProxyAjax extends Store {
  constructor(opts) {
    super(opts)
    this.reader = {
      type: 'json',
      root: 'data',
      total: 'totalCount'
    }
    // if (!this.opts.url) {
    //   throw Error('参数缺少url')
    // }
    this._searchParams = {}
    this._filterParam = [
      data => {
        return Object.assign(data || {}, this._searchParams)
      },
      data => {
        const obj = {}
        for (const k in data) {
          if (data[k] !== undefined && data[k] !== '') {
            obj[k] = data[k]
          }
        }
        return obj
      }
    ].concat(this.opts.filterParam)
      .filter(fn => _toString.call(fn) === "[object Function]")

    if (this.opts.reader) {
      if (this.opts.reader.root) this.reader.root = this.opts.reader.root
      if (this.opts.reader.total) this.reader.total = this.opts.reader.total
    }
    // 通知 created event
    this.emit('created', this)
  }
  request(...args) {
    return request.apply(this, args)
  }
  filterParam(data) {
    return this._filterParam.reduce((data, fn) => fn(data), data)
  }
  formatData(res) {
    const data = res && res[this.reader.root] || []
    const total = res && res[this.reader.total] || 0
    // this._data = data
    // this._total = total
    this.emit('loaded', { data, total })
    return { data, total }
  }
  // eslint-disable-next-line
  read(paramObj) {
    const _param = this.filterParam(Object.assign({ start: 1, limit: 10 }, paramObj || {}))
    const {
      method = (this.opts.method || 'get'),
      headers = (this.opts.headers || {}),
      url = this.opts.url,
      params,
      data,
      ...otherData
    } = _param

    if (!url) {
      return new Promise((resolve, reject) => {
        reject("url is null")
      })
    }
    const _method = method.toLowerCase()

    if (_method === 'get') {
      return this._doRequest({
        url,
        headers,
        method,
        params: params || data || otherData
      })
    }

    if (_method === 'post') {
      if (!headers.hasOwnProperty('Content-Type')) {
        headers["Content-Type"] = "application/x-www-form-urlencoded"
      }
      if (params && data) {
        return this._doRequest({
          url,
          headers,
          method,
          params,
          data
        })
      } else {
        const { start, limit, ...resetData } = otherData
        return this._doRequest({
          url,
          headers,
          method,
          params: params || { start, limit },
          data: data || resetData
        })
      }
    }
  }
  _doRequest(config) {
    return request(config).then((res) => {
      return this.formatData(res)
    })
  }
}

export default ProxyAjax
